<template>
  <div class="approval-flow">
    <div class="flow-header" v-if="showHeader">
      <h3 class="flow-title">
        <span class="title-icon">🔄</span>
        审批流程
      </h3>
      <div class="flow-summary" v-if="approvalFlow">
        <el-tag :type="getOverallStatusType(approvalFlow.currentStatus || '')" class="status-tag">
          {{ getOverallStatusText(approvalFlow.currentStatus || '') }}
        </el-tag>
        <span class="flow-info">
          共{{ approvalFlow.approvalRecords?.length || 0 }}步 · 
          耗时{{ calculateTotalDuration() }}
        </span>
      </div>
    </div>

    <div class="flow-content" v-loading="loading">
      <div v-if="!approvalFlow || !approvalFlow.approvalRecords?.length" class="empty-state">
        <el-empty description="暂无审批记录" />
      </div>

      <div v-else class="flow-timeline">
        <el-timeline>
          <el-timeline-item
            v-for="(record, index) in approvalFlow.approvalRecords"
            :key="record.id"
            :timestamp="formatApprovalTime(record.approvalTime)"
            :type="getTimelineType(record.decision)"
            :color="getTimelineColor(record.decision)"
            :size="size"
            placement="top"
            :hollow="isCurrentStep(record, index)"
          >
            <div class="approval-record">
              <!-- 审批头部信息 -->
              <div class="record-header">
                <div class="approver-info">
                  <div class="approver-main">
                    <span class="approver-name">{{ record.approverName }}</span>
                    <el-tag 
                      v-if="record.approverRole" 
                      size="small" 
                      type="info" 
                      class="role-tag"
                    >
                      {{ record.approverRole }}
                    </el-tag>
                  </div>
                  <div class="step-info">
                    第{{ record.stepSequence }}步
                    <span v-if="record.processingDurationMinutes" class="duration">
                      · 用时{{ record.processingDurationMinutes }}分钟
                    </span>
                  </div>
                </div>
                
                <div class="decision-info">
                  <el-tag 
                    :type="getDecisionTagType(record.decision)" 
                    class="decision-tag"
                    :effect="isCurrentStep(record, index) ? 'dark' : 'light'"
                  >
                    <el-icon class="decision-icon">
                      <component :is="getDecisionIcon(record.decision)" />
                    </el-icon>
                    {{ getDecisionText(record.decision) }}
                  </el-tag>
                </div>
              </div>

              <!-- 状态变更信息 -->
              <div class="status-change" v-if="record.statusBefore || record.statusAfter">
                <div class="status-flow">
                  <el-tag size="small" type="info">{{ record.statusBefore || '初始' }}</el-tag>
                  <el-icon class="arrow-icon"><Right /></el-icon>
                  <el-tag size="small" :type="getStatusTagType(record.statusAfter)">
                    {{ record.statusAfter }}
                  </el-tag>
                </div>
              </div>

              <!-- 审批意见 -->
              <div class="approval-comments" v-if="record.approvalComments">
                <div class="comments-label">审批意见：</div>
                <div class="comments-content">{{ record.approvalComments }}</div>
              </div>

              <!-- 附件信息 -->
              <div class="attachments" v-if="record.attachmentUrls?.length">
                <div class="attachments-label">附件：</div>
                <div class="attachments-list">
                  <el-link 
                    v-for="(url, urlIndex) in record.attachmentUrls" 
                    :key="urlIndex"
                    type="primary" 
                    :href="url" 
                    target="_blank"
                    class="attachment-link"
                  >
                    <el-icon><Document /></el-icon>
                    附件{{ urlIndex + 1 }}
                  </el-link>
                </div>
              </div>

              <!-- 技术信息（仅在详细模式下显示） -->
              <div class="technical-info" v-if="showTechnicalInfo">
                <el-collapse>
                  <el-collapse-item title="技术信息" name="tech">
                    <div class="tech-details">
                      <div class="tech-item" v-if="record.approvalMethod">
                        <span class="tech-label">审批方式：</span>
                        <span class="tech-value">{{ record.approvalMethod }}</span>
                      </div>
                      <div class="tech-item" v-if="record.ipAddress">
                        <span class="tech-label">IP地址：</span>
                        <span class="tech-value">{{ record.ipAddress }}</span>
                      </div>
                      <div class="tech-item" v-if="record.userAgent">
                        <span class="tech-label">用户代理：</span>
                        <span class="tech-value">{{ record.userAgent }}</span>
                      </div>
                      <div class="tech-item">
                        <span class="tech-label">记录时间：</span>
                        <span class="tech-value">{{ formatDateTime(record.createTime) }}</span>
                      </div>
                    </div>
                  </el-collapse-item>
                </el-collapse>
              </div>
            </div>
          </el-timeline-item>
        </el-timeline>
      </div>

      <!-- 流程统计信息 -->
      <div class="flow-stats" v-if="showStats && approvalFlow">
        <el-divider content-position="center">流程统计</el-divider>
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-label">总步数</div>
              <div class="stat-value">{{ approvalFlow.approvalRecords?.length || 0 }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-label">总耗时</div>
              <div class="stat-value">{{ calculateTotalDuration() }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-label">平均用时</div>
              <div class="stat-value">{{ calculateAverageDuration() }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-label">当前状态</div>
              <div class="stat-value">{{ approvalFlow.currentStatus }}</div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { 
  Right, 
  Document, 
  Check, 
  Close, 
  Upload, 
  Download,
  RefreshRight 
} from '@element-plus/icons-vue'
import type { ApprovalFlowDto, PurchaseOrderApprovalRecordDto } from '@/types/console'

// Props
interface Props {
  approvalFlow?: ApprovalFlowDto
  loading?: boolean
  showHeader?: boolean
  showStats?: boolean
  showTechnicalInfo?: boolean
  size?: 'large' | 'default' | 'small'
  mode?: 'full' | 'simple' | 'compact'
}

const props = withDefaults(defineProps<Props>(), {
  loading: false,
  showHeader: true,
  showStats: true,
  showTechnicalInfo: false,
  size: 'default',
  mode: 'full'
})

// Emits
const emit = defineEmits<{
  'record-click': [record: PurchaseOrderApprovalRecordDto]
  'refresh': []
}>()

// 计算属性
  const sortedRecords = computed(() => {
    if (!props.approvalFlow?.approvalRecords) return []
    return [...props.approvalFlow.approvalRecords].sort((a, b) => a.stepSequence - b.stepSequence)
  })

// 方法
const isCurrentStep = (record: PurchaseOrderApprovalRecordDto, index: number) => {
  if (!props.approvalFlow) return false
  return props.approvalFlow.currentStep === record.stepSequence
}

const calculateTotalDuration = () => {
  if (!props.approvalFlow?.approvalRecords?.length) return '0分钟'
  
  const totalMinutes = props.approvalFlow.approvalRecords.reduce(
    (sum, record) => sum + (record.processingDurationMinutes || 0), 
    0
  )
  
  if (totalMinutes < 60) {
    return `${totalMinutes}分钟`
  } else if (totalMinutes < 1440) {
    const hours = Math.floor(totalMinutes / 60)
    const minutes = totalMinutes % 60
    return `${hours}小时${minutes > 0 ? minutes + '分钟' : ''}`
  } else {
    const days = Math.floor(totalMinutes / 1440)
    const hours = Math.floor((totalMinutes % 1440) / 60)
    return `${days}天${hours > 0 ? hours + '小时' : ''}`
  }
}

const calculateAverageDuration = () => {
  if (!props.approvalFlow?.approvalRecords?.length) return '0分钟'
  
  const totalMinutes = props.approvalFlow.approvalRecords.reduce(
    (sum, record) => sum + (record.processingDurationMinutes || 0), 
    0
  )
  
  const avgMinutes = Math.round(totalMinutes / props.approvalFlow.approvalRecords.length)
  return `${avgMinutes}分钟`
}

// 格式化方法
const formatApprovalTime = (time: string) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 样式和类型判断
const getOverallStatusType = (status: string | undefined) => {
  if (!status) return 'info'
  const typeMap: Record<string, string> = {
    '审批中': 'primary',
    '已审批': 'success',
    '已拒绝': 'danger',
    '已撤回': 'warning'
  }
  return typeMap[status] || 'info'
}

const getOverallStatusText = (status: string | undefined) => {
  return status || '未知状态'
}

const getTimelineType = (decision: string) => {
  const typeMap: Record<string, string> = {
    'submit': 'primary',
    '通过': 'success',
    '驳回': 'danger',
    'withdraw': 'warning'
  }
  return typeMap[decision] || 'primary'
}

const getTimelineColor = (decision: string) => {
  const colorMap: Record<string, string> = {
    'submit': '#409eff',
    '通过': '#67c23a',
    '驳回': '#f56c6c',
    'withdraw': '#e6a23c'
  }
  return colorMap[decision] || '#409eff'
}

const getDecisionTagType = (decision: string) => {
  const typeMap: Record<string, string> = {
    'submit': 'primary',
    '通过': 'success',
    '驳回': 'danger',
    'withdraw': 'warning'
  }
  return typeMap[decision] || 'primary'
}

const getDecisionText = (decision: string) => {
  const textMap: Record<string, string> = {
    'submit': '提交',
    '通过': '同意',
    '驳回': '拒绝',
    'withdraw': '撤回'
  }
  return textMap[decision] || decision
}

const getDecisionIcon = (decision: string) => {
  const iconMap: Record<string, any> = {
    'submit': Upload,
    '通过': Check,
    '驳回': Close,
    'withdraw': RefreshRight
  }
  return iconMap[decision] || Upload
}

const getStatusTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    '草稿': 'info',
    '待审批': 'warning',
    '审批中': 'primary',
    '已审批': 'success',
    '已拒绝': 'danger',
    '已撤回': 'info'
  }
  return typeMap[status] || 'info'
}
</script>

<style scoped>
.approval-flow {
  width: 100%;
}

.flow-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
  padding-bottom: 1rem;
  border-bottom: 1px solid #ebeef5;
}

.flow-title {
  margin: 0;
  font-size: 1.2rem;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.title-icon {
  font-size: 1.3rem;
}

.flow-summary {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.status-tag {
  font-weight: 600;
}

.flow-info {
  color: #606266;
  font-size: 0.875rem;
}

.flow-content {
  position: relative;
}

.empty-state {
  text-align: center;
  padding: 2rem;
}

.flow-timeline {
  padding: 1rem 0;
}

.approval-record {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 1rem;
  border: 1px solid #e9ecef;
  margin-bottom: 0.5rem;
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 0.75rem;
}

.approver-info {
  flex: 1;
}

.approver-main {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-bottom: 0.25rem;
}

.approver-name {
  font-weight: 600;
  color: #303133;
  font-size: 0.95rem;
}

.role-tag {
  font-size: 0.75rem;
}

.step-info {
  color: #909399;
  font-size: 0.8rem;
}

.duration {
  color: #67c23a;
}

.decision-info {
  display: flex;
  align-items: center;
}

.decision-tag {
  font-weight: 600;
}

.decision-icon {
  margin-right: 0.25rem;
}

.status-change {
  margin-bottom: 0.75rem;
}

.status-flow {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.arrow-icon {
  color: #909399;
  font-size: 0.875rem;
}

.approval-comments {
  margin-bottom: 0.75rem;
}

.comments-label {
  font-size: 0.875rem;
  color: #606266;
  margin-bottom: 0.25rem;
}

.comments-content {
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 0.75rem;
  color: #303133;
  line-height: 1.5;
  white-space: pre-wrap;
}

.attachments {
  margin-bottom: 0.75rem;
}

.attachments-label {
  font-size: 0.875rem;
  color: #606266;
  margin-bottom: 0.25rem;
}

.attachments-list {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
}

.attachment-link {
  display: flex;
  align-items: center;
  gap: 0.25rem;
  padding: 0.25rem 0.5rem;
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  font-size: 0.875rem;
}

.technical-info {
  margin-top: 0.5rem;
}

.tech-details {
  padding: 0.5rem;
  background: #fafafa;
  border-radius: 4px;
}

.tech-item {
  display: flex;
  margin-bottom: 0.25rem;
}

.tech-item:last-child {
  margin-bottom: 0;
}

.tech-label {
  font-size: 0.75rem;
  color: #909399;
  width: 80px;
  flex-shrink: 0;
}

.tech-value {
  font-size: 0.75rem;
  color: #606266;
  word-break: break-all;
}

.flow-stats {
  margin-top: 2rem;
  padding-top: 1rem;
}

.stat-item {
  text-align: center;
  padding: 1rem;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.stat-label {
  font-size: 0.875rem;
  color: #606266;
  margin-bottom: 0.5rem;
}

.stat-value {
  font-size: 1.25rem;
  font-weight: 600;
  color: #303133;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .flow-header {
    flex-direction: column;
    gap: 1rem;
    align-items: flex-start;
  }

  .flow-summary {
    width: 100%;
    justify-content: space-between;
  }

  .record-header {
    flex-direction: column;
    gap: 0.75rem;
  }

  .approver-main {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.25rem;
  }

  .status-flow {
    flex-wrap: wrap;
  }

  .attachments-list {
    flex-direction: column;
  }

  .stat-item {
    margin-bottom: 1rem;
  }
}

/* 紧凑模式 */
.approval-flow.compact .approval-record {
  padding: 0.75rem;
  margin-bottom: 0.25rem;
}

.approval-flow.compact .flow-timeline {
  padding: 0.5rem 0;
}

/* 简单模式 */
.approval-flow.simple .technical-info,
.approval-flow.simple .flow-stats {
  display: none;
}
</style> 